package main;

/**
 * @author Paulo -> 42243
 * @author Daniela -> 42439
 *
 */

import java.io.*;
import java.util.*;
import entidades.*;
import shared.*;

public class Main {
	static Scanner in = new Scanner(System.in);
	static int numGrutas = 0;
	static int numPilhagens = 0;
	static int numExploradores = 0;
	static int exploradorQuantMax = 0;
	static int numPiratas = 0;
	static int pirataQuantMax = 0;
	static Thread capitao;
	static Thread[] exploradores;
	
	public static void main(String[] args) throws InterruptedException, IOException {
		
		
		//para testar a parte grafica comentar apartir daqui
		System.out.println("####################### ILHA PIRATA #######################");
		System.out.print("Ficheiro de Configuração: ");
		String path = in.nextLine();
		
		if (new File(path).exists() && fileFilter(path)) {
			readConfigurationFile(path);
			System.out.print("Configurado!\n\n");
			System.out.println("INICIO DA HIST�RIA!!!");
			Preferences.log.add("INICIO DA HIST�RIA!!!");
			
			Main.initialization();
			
			Main.start();
			
			System.out.println("FIM DA HIST�RIA!!!");
			Preferences.log.add("FIM DA HIST�RIA!!!");
			
			System.out.print("Exportar para: ");
			String exportPath = in.nextLine();
			
			if (exportPath!=null) {
				System.out.print("Exportado!");
				writeFile(exportPath);
			}
		}
		else {
			System.out.println("ERRO: O Ficheiro n�o existe, ou ent�o n�o � compativel!");
		}
		
		
		//at� aqui
		
		//descomentar este codigo para experimentar com interface gr�fica, e nao esquecer de comentar o de cima para nao have interferencia
		//new Window();
		
		System.out.print("Aplica��o Terminada!");
		System.exit(0);
	}
	
	public static void readConfigurationFile(String name) throws FileNotFoundException {
		Scanner f = new Scanner(new File(name));
		ArrayList<String> lines = new ArrayList<String>();
		String[] options;
		
		while(f.hasNext()){
			lines.add(f.nextLine());
		}
		
		options = new String[lines.size()];
		lines.toArray(options);
		
		/* Ordem das Linhas
		 * 1 numGrutas
		 * 2 numPilagens
		 * 3 numExploradores
		 * 4 exploradorQuantMax
		 * 5 numPiratas
		 * 6 piratasQuantMax
		*/
		for (int i=0; i<options.length; i++) {
			options[i] = (options[i].split("="))[1];
		}
		
		numGrutas = Integer.valueOf(options[0]);
		numPilhagens = Integer.valueOf(options[1]);
		numExploradores = Integer.valueOf(options[2]);
		exploradorQuantMax = Integer.valueOf(options[3]);
		numPiratas = Integer.valueOf(options[4]);
		pirataQuantMax = Integer.valueOf(options[5]);
	}
	
	public static void writeFile(String name) {
		FileWriter f;
		try {
			f = new FileWriter(new File(name));
		
			for (Iterator<String> iterator = Preferences.log.iterator(); iterator.hasNext();) {
				String line = (String) iterator.next();
				f.write(line+"\r\n");
			}
			
			f.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	public static boolean fileFilter(String name) {
		String[] file = name.split("\\.");
		String extension = file[file.length-1];
		
		if (extension.equals("txt"))
			return true;
		else
			return false;
	}
	
	public static boolean isConfigured() {
		if (numGrutas==0 && numPilhagens==0 && numExploradores==0 && exploradorQuantMax==0 && numPiratas==0 && pirataQuantMax==0)
			return false;
		else
			return true;
	}
	
	public static void initialization() {
		Preferences.barcoPirata = new BarcoPirata();
		Preferences.barcoExplorador = new BarcoExplorador();
		Preferences.ilha = new Ilha(numGrutas);
		Preferences.barcosTesouro = new BarcoTesouro[numPilhagens];
		Preferences.exploradores = new Explorador[numExploradores];
		Preferences.frota = new Pirata[numPiratas];
		Preferences.capitao = new Capitao(Preferences.frota, Preferences.ilha);
		exploradores = new Thread[numExploradores];
		capitao = new Thread(Preferences.capitao);	
		
		int[] valores = dividirParaConquistar(Preferences.exploradores.length, Preferences.ilha.getGrutas().length);
		
		int indice = 0;
		for (int i=0; i<Preferences.exploradores.length; i++) {
			Preferences.exploradores[i] = new Explorador((i+1), exploradorQuantMax, indice, valores[i]);
			indice = indice + valores[i];
		}
		
		
		for (int i=0; i<Preferences.barcosTesouro.length; i++)
			Preferences.barcosTesouro[i] = new BarcoTesouro((int) (new Random().nextDouble() * 250));
		
		for (int i=0; i<Preferences.frota.length; i++)
			Preferences.frota[i] = new Pirata(i+1, pirataQuantMax);
		
		for (int i=0; i<exploradores.length; i++)
			exploradores[i] = new Thread(Preferences.exploradores[i]);
	}
	
	public static void start() throws InterruptedException {
		capitao.start();
		capitao.join();
		
		for (Thread t: exploradores)
			t.start();
		
		for (Thread t: exploradores)
			t.join();
	}
	
	private static int[] dividirParaConquistar(int numE, int numG) {
		int[] temp = new int[numE];
		int n = numG;
		
		do{
			for (int i=0; i<numE; i++) {
				if (n>0) {
					temp[i]++;
					n--;
				}
			}
		}while(n>0);
		
		return temp;
	}
	
	@SuppressWarnings("deprecation")
	public static void setList(Collection<String> collection) {
		String[] temp = new String[collection.size()];
		collection.toArray(temp);
		Window.list.setListData(temp);
		Window.list.show();
	}
}
